package com.jk;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.smart4j.framework.helper.DatabaseHelper;
import org.smart4j.framework.util.CastUtil;
import org.smart4j.plugin.security.SmartSecurity;

/**
 * 应用安全控制
 *
 * @author huangyong
 * @since 1.0.0
 */
public class AppSecurity implements SmartSecurity {


    public String getPassword(String username) {
        String sql = "SELECT password FROM system_user WHERE username = '" + username + "' and delete_flag = '0'";
        Map result =  DatabaseHelper.query(sql);
        return CastUtil.castString(result.get("password"));
    }

    public Set<String> getRoleNameSet(String username) {
        String sql = "SELECT r.role_name " +
                "FROM system_user u, system_user_role ur, system_role r " +
                "WHERE u.id = ur.user_id AND " +
                "r.id = ur.role_id AND " +
                "u.username = '" + username + "' AND " +
                "u.delete_flag = '0'AND " +
                "ur.delete_flag = '0'AND " +
                "r.delete_flag = '0'";
        return DatabaseHelper.queryStringSet(sql);
    }

    public Set<String> getPermissionNameSet(String roleName,String userName) {
        String roleSql = "SELECT p.permission_name " +
                "FROM system_role r,system_role_permission rp, system_permission p " +
                "WHERE r.id = rp.role_id AND " +
                "p.id = rp.permission_id AND " +
                "r.role_name = '" + roleName + "' AND " +
                "r.delete_flag = '0' AND " +
                "rp.delete_flag = '0' AND " +
                "p.delete_flag = '0'";

        String userSql = "SELECT " +
                "t3.permission_name " +
                "FROM " +
                "system_user t1 " +
                "left JOIN " +
                "system_user_permission t2 " +
                "ON " +
                "t1.id = t2.user_id " +
                "LEFT JOIN " +
                "system_permission t3 " +
                "ON " +
                "t3.id = t2.permission_id " +
                "WHERE " +
                "t1.username = '"+userName+" '" +
                "AND t1.delete_flag = '0' " +
                "AND t2.delete_flag = '0' " +
                "AND t3.delete_flag = '0' ";

        Set<String> rolePermissionSet = DatabaseHelper.queryStringSet(roleSql);
        Set<String> userPermissionSet = DatabaseHelper.queryStringSet(userSql);

        Set<String > permissionSet = new HashSet<>();
        permissionSet.addAll(rolePermissionSet);
        permissionSet.addAll(userPermissionSet);


        return permissionSet;
    }

    @Override
    public void handleAnthzException() {

    }

    @Override
    public void handleAuthcException() {

    }
}
